<script lang="ts" setup>
import { ref, reactive, computed, watch, h } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Card, Table, Button, Space, Input, Select, DatePicker, Tag, Form, message } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';

import { getTenantTaskListApi, type TaskApi } from '#/api/core/task';
import { getTenantDetailApi } from '#/api/core/tenant';

type DateRangeValue = [string, string] | [];

const route = useRoute();
const router = useRouter();

const tenantId = ref<string>('');
const tenantName = ref<string>(
  typeof route.query.tenantName === 'string' ? route.query.tenantName : '',
);
const loading = ref(false);
const tasks = ref<TaskApi.TaskRecord[]>([]);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const filters = reactive({
  search: '',
  status: '' as '' | 'inactive' | 'active',
});

const dateRange = ref<DateRangeValue>([]);

const statusOptions = [
  { label: '生效中', value: 'active' },
  { label: '未生效', value: 'inactive' },
];

const cardTitle = computed(() =>
  tenantName.value ? `租户任务 - ${tenantName.value}` : '租户任务',
);

const formatCurrency = (value: string | number | null | undefined) => {
  const num = Number(value ?? 0);
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

const formatDateRange = (start?: string | null, end?: string | null) => {
  if (!start && !end) {
    return '—';
  }
  if (!start || !end) {
    return start || end || '—';
  }
  return `${start} ~ ${end}`;
};

const formatDateTime = (value?: string | null) => {
  if (!value) {
    return '—';
  }
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }
  const pad = (num: number) => (num < 10 ? `0${num}` : `${num}`);
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
    date.getHours(),
  )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};

const columns: TableColumnsType<TaskApi.TaskRecord> = [
  { title: '任务ID', dataIndex: 'id', key: 'id', width: 140, ellipsis: true },
  { title: '任务名称', dataIndex: 'name', key: 'name', width: 200, ellipsis: true },
  { title: '任务类型', dataIndex: 'service_type', key: 'service_type', width: 140 },
  {
    title: '任务状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
    customRender: ({ record }) => {
      const statusMap: Record<string, { color: string; text: string }> = {
        active: { color: 'green', text: '生效中' },
        inactive: { color: 'default', text: '未生效' },
      };
      const status = statusMap[record.status] ?? {
        color: 'default',
        text: record.status ?? '未知',
      };
      return h(Tag, { color: status.color }, () => status.text);
    },
  },
  {
    title: '任务周期',
    key: 'period',
    width: 220,
    customRender: ({ record }) => formatDateRange(record.start_time, record.end_time),
  },
  {
    title: '任务计费',
    key: 'fee',
    width: 200,
    customRender: ({ record }) => {
      const unitLabel = record.billing_unit ? `/${record.billing_unit}` : '';
      return `¥${formatCurrency(record.min_fee)} ~ ¥${formatCurrency(record.max_fee)}${unitLabel}`;
    },
  },
  {
    title: '工作地点',
    dataIndex: 'work_location',
    key: 'work_location',
    width: 220,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 200,
    customRender: ({ record }) => formatDateTime(record.created_at),
  },
  {
    title: '操作',
    key: 'actions',
    width: 140,
    fixed: 'right',
    customRender: ({ record }) =>
      h(
        Button,
        {
          type: 'link',
          size: 'small',
          onClick: () => goToTaskApplications(record),
        },
        () => '查看报名',
      ),
  },
];

const tablePagination = computed(() => ({
  current: pagination.current,
  pageSize: pagination.pageSize,
  total: pagination.total,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
}));

const fetchTenantDetail = async (id: string) => {
  try {
    const detail = await getTenantDetailApi(id);
    tenantName.value = detail.tenant?.name ?? tenantName.value;
  } catch (error) {
    console.error('获取租户详情失败', error);
    message.error('获取租户详情失败');
  }
};

const goToTaskApplications = (record: TaskApi.TaskRecord) => {
  router.push({
    name: 'TenantTaskApplications',
    params: { tenantId: tenantId.value, taskId: record.id },
    query: {
      tenantName: tenantName.value,
      taskName: record.name,
    },
  });
};

const fetchTaskList = async (id: string) => {
  if (!id) {
    return;
  }
  loading.value = true;
  try {
    const [start, end] = Array.isArray(dateRange.value) ? dateRange.value : [];
    const response = await getTenantTaskListApi(id, {
      page: pagination.current,
      per_page: pagination.pageSize,
      search: filters.search.trim() || undefined,
      status: filters.status || undefined,
      start_date: start || undefined,
      end_date: end || undefined,
    });

    tasks.value = (response.data ?? []).map((item) => ({
      ...item,
      id: String(item.id ?? ''),
      tenant_id: String(item.tenant_id ?? id),
    }));
    pagination.total = response.total ?? 0;
    if (response.per_page) {
      pagination.pageSize = Number(response.per_page);
    }
    pagination.current = response.current_page ?? pagination.current;
  } catch (error) {
    console.error('获取任务列表失败', error);
    message.error('获取任务列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchTaskList(tenantId.value);
};

const handleReset = () => {
  filters.search = '';
  filters.status = '';
  dateRange.value = [];
  pagination.current = 1;
  fetchTaskList(tenantId.value);
};

const handleTableChange = (pag: { current?: number; pageSize?: number }) => {
  pagination.current = pag.current ?? pagination.current;
  pagination.pageSize = pag.pageSize ?? pagination.pageSize;
  fetchTaskList(tenantId.value);
};

const handleBack = () => {
  router.push({ name: 'TenantManagement' });
};

watch(
  () => route.query.tenantName,
  (newVal) => {
    if (typeof newVal === 'string') {
      tenantName.value = newVal;
    }
  },
  { immediate: true },
);

watch(
  () => route.params.tenantId,
  (newVal) => {
    const id = newVal ? String(newVal) : '';
    tenantId.value = id;
    filters.search = '';
    filters.status = '';
    dateRange.value = [];
    pagination.current = 1;
    if (!id) {
      tasks.value = [];
      tenantName.value = '';
      return;
    }
    fetchTenantDetail(id);
    fetchTaskList(id);
  },
  { immediate: true },
);
</script>

<template>
  <div class="p-5 space-y-4">
    <Card>
      <Form layout="inline" :model="filters">
        <Form.Item label="关键词">
          <Input
            v-model:value="filters.search"
            allow-clear
            placeholder="任务名称 / 工作内容 / 工作地点"
            style="width: 240px"
            @pressEnter="handleSearch"
          />
        </Form.Item>
        <Form.Item label="任务状态">
          <Select
            v-model:value="filters.status"
            :options="statusOptions"
            allow-clear
            placeholder="请选择"
            style="width: 160px"
          />
        </Form.Item>
        <Form.Item label="任务周期">
          <DatePicker.RangePicker
            v-model:value="dateRange"
            allow-clear
            value-format="YYYY-MM-DD"
            style="width: 260px"
            :placeholder="['开始日期', '结束日期']"
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch" :loading="loading">查询</Button>
            <Button @click="handleReset">重置</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>

    <Card :title="cardTitle" :bordered="false">
      <template #extra>
        <Button @click="handleBack">返回</Button>
      </template>
      <Table
        :columns="columns"
        :data-source="tasks"
        :loading="loading"
        row-key="id"
        :pagination="tablePagination"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      />
    </Card>
  </div>
</template>
